package com.jvbc.xoso;

import java.util.ArrayList;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import com.jvbc.xoso.bean.RSSItem;


public class RSSParser extends DefaultHandler{
	private static final String TAG_ITEM = "item";
	private static final String[] xmlTags = {"title", "description",
		"link", "pubDate"};
	private RSSItem currentItem = null;
	private ArrayList<RSSItem> itemArray = null;
	private int currentIndex = -1;
	private boolean isParsing = false;
	private StringBuilder builder = new StringBuilder();
	
	public RSSParser(ArrayList<RSSItem> itemArray) {
		super();
		this.itemArray = itemArray;
	}
	@Override
	public void characters(char[] ch, int start, int length)  throws
	SAXException{
		super.characters(ch, start, length);
		
		if (isParsing && currentIndex != -1 && builder!=null) {
			builder.append(ch, start, length);
		}
	}
	
	@Override
	public void startElement(String uri, String localName, String qName, 
			Attributes attributes) throws SAXException{
		super.startElement(uri, localName, qName, attributes);
		
		if (localName.equalsIgnoreCase(TAG_ITEM)) {
			currentItem = new RSSItem();
			currentIndex = -1;
			isParsing = true;
			itemArray.add(currentItem);
		} else {
			currentIndex = itemIndexFromString(localName);
			builder = null;
			if (currentIndex != -1) {
				builder = new StringBuilder();
			}
		}
	}
	@Override
	public void endElement(String uri, String localName,
			String qName) throws SAXException{
		super.endElement(uri, localName, qName);
		if (localName.equalsIgnoreCase(TAG_ITEM)) {
			isParsing = false;
		} else if(currentIndex != -1){
			if (isParsing) {
				switch (currentIndex) {
				case 0:
					currentItem.setTitle(builder.toString());
					break;
				case 1:
					currentItem.setDescription(builder.toString());
					break;	
				case 2:
					currentItem.setLink(builder.toString());				
					break;
				case 3:
					currentItem.setPubDate(builder.toString());
					break;
				}
			}
		}
		
	}
	private int itemIndexFromString(String localName) {
		int itemIndex = -1;
		for(int index = 0; index < xmlTags.length; index++) {
			if (localName.equalsIgnoreCase(xmlTags[index])) {
				itemIndex = index;
				break;
			}
		}
		
		return itemIndex;
	}

}
